package com.example.service;

import com.example.dto.WebSocketMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

/**
 * WebSocket服务类
 * 用于发送WebSocket消息
 */
@Service
@Slf4j
public class WebSocketService {
    
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    /**
     * 发送广播消息给所有在线用户
     */
    public void sendBroadcastMessage(WebSocketMessage message) {
        try {
            log.info("发送广播消息: {}", message.getTitle());
            messagingTemplate.convertAndSend("/topic/notifications", message);
        } catch (Exception e) {
            log.error("发送广播消息失败", e);
        }
    }
    
    /**
     * 发送私人消息给指定用户
     */
    public void sendPrivateMessage(Long userId, WebSocketMessage message) {
        try {
            log.info("发送私人消息给用户 {}: {}", userId, message.getTitle());
            messagingTemplate.convertAndSendToUser(
                userId.toString(), 
                "/queue/notifications", 
                message
            );
        } catch (Exception e) {
            log.error("发送私人消息失败", e);
        }
    }
    
    /**
     * 发送通知消息（广播）
     */
    public void sendNoticeNotification(String title, String content, Object data, Long senderId, String senderName) {
        WebSocketMessage message = WebSocketMessage.createNoticeMessage(title, content, data, senderId, senderName);
        sendBroadcastMessage(message);
    }
    
    /**
     * 发送系统消息（广播）
     */
    public void sendSystemNotification(String title, String content, String level) {
        WebSocketMessage message = WebSocketMessage.createSystemMessage(title, content, level);
        sendBroadcastMessage(message);
    }
    
    /**
     * 发送私人通知
     */
    public void sendPrivateNotification(Long userId, String title, String content, Object data, 
                                       Long senderId, String senderName) {
        WebSocketMessage message = WebSocketMessage.createPrivateMessage(title, content, data, senderId, senderName, userId);
        sendPrivateMessage(userId, message);
    }
    
    /**
     * 发送通知发布消息
     */
    public void sendNoticePublishedNotification(String noticeTitle, String publisherName, Long publisherId) {
        String title = "新通知发布";
        String content = String.format("管理员 %s 发布了新通知：%s", publisherName, noticeTitle);
        sendNoticeNotification(title, content, null, publisherId, publisherName);
    }
    
    /**
     * 发送通知下线消息
     */
    public void sendNoticeOfflineNotification(String noticeTitle, String publisherName, Long publisherId) {
        String title = "通知已下线";
        String content = String.format("管理员 %s 下线了通知：%s", publisherName, noticeTitle);
        sendNoticeNotification(title, content, null, publisherId, publisherName);
    }
}
